package org.shj.netty.chartper3;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class TimeClientHandler extends SimpleChannelInboundHandler<ByteBuf>{
	
	private final ByteBuf firstMsg;
	
	public TimeClientHandler(){
		byte[] req = "QUERY TIME ORDER".getBytes();
		firstMsg = Unpooled.buffer(req.length);
		firstMsg.writeBytes(req);
	}
	
	//客户端连接服务器后被调用
	public void channelActive(ChannelHandlerContext ctx){
		ctx.writeAndFlush(firstMsg);
	}
	
	//从服务器接收到数据后被调用
	public void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception{
		byte[] req = new byte[msg.readableBytes()];
		msg.readBytes(req);
		String body = new String(req, "UTF-8");
		System.out.println("Now is: " + body);
		
		
		ctx.close();
	}
	
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
		cause.printStackTrace();
		ctx.close();
	}
}
